package fishBids.group3.behaviour.bank;

import es.upm.agents.ontology.ToGetMoneyResponse;
import fishBids.group3.AgBank;
import fishBids.group3.behaviour.bank.model.Account;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;
import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class BankGetMoneyBehaviour extends CyclicBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2472621384661749131L;
	
	public BankGetMoneyBehaviour(AgBank agBank, Codec codec, Ontology ontology){
		this.agBank = agBank;
		this.codec =  codec;
		this.ontology = ontology;
		
	}

	@Override
	public void action() {

		MessageTemplate mt1 = MessageTemplate.and( 
		    	MessageTemplate.MatchLanguage(codec.getName()), 
		    	MessageTemplate.and(MessageTemplate.MatchOntology(ontology.getName()),
		    	MessageTemplate.and(MessageTemplate.MatchProtocol(Constants.GET_MONEY),
		    	MessageTemplate.MatchPerformative(ACLMessage.QUERY_REF)))); 
		
			ACLMessage msg = this.agBank.receive(mt1);
		if (msg != null){
//				System.out.println( "Bank>>> GetMoney QUERY_REF message arrived");
				
				Account account = (Account)this.agBank.getAgentsAccounts().get(msg.getSender().getName());
				if(account != null){
					ToGetMoneyResponse toGetMoneyResponse = new ToGetMoneyResponse();
					toGetMoneyResponse.setMoneyAmount((float) account.getBalance());
								
					//TODO retrieve the money in the bank account
					Utils.sendMessageWithConcept(ACLMessage.INFORM,
								codec, ontology, msg.getSender(),
							Constants.GET_MONEY, this.agBank,
							toGetMoneyResponse);
					//System.out.println( "Bank>>>  Sending getMoney INFORM" );
					return;
				}else {
					//System.out.println( "Bank>>>  Sending getMoney REFUSE" );
					Utils.sendMessage(ACLMessage.REFUSE,
							codec, ontology, msg.getSender(),
						Constants.GET_MONEY, this.agBank);
					return;
				
				}								
			
			
		}

		}



	AgBank agBank;
	Codec codec;
	Ontology ontology;

}
